﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.Event.NCL;
using CPPEI.Coolzon.Event.UI;
using CPPEI.Coolzon.Service.Contract;
using CPPEI.Coolzon.ServiceProxy;
using CPPEI.Coolzon.ServiceProxy.MainServiceRef;
using CPPEI.Coolzon.UI.Data;
using CPPEI.Coolzon.UI.Event;
using CPPEI.Coolzon.UI.Views;
using CPPEI.Coolzon.UI.Views.EventProxies;
using CPPEI.Coolzon.UI.Views.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.UI
{
    /// <summary>
    /// 远程的事件代理
    /// </summary>
    public partial class RemoteEventProxy : EventProxy
    {
        /// <summary>
        /// 最新一次打开的场景
        /// </summary>
        private string _latestOpenScene;
        private long _latestOpenSceneTicks;

        #region singleton
        private static RemoteEventProxy s_instance;

        public static RemoteEventProxy Instance
        {
            get
            {
                if (s_instance == null)
                {
                    s_instance = new RemoteEventProxy();
                }
                return s_instance;
            }
        }

        private RemoteEventProxy()
        {
        }
        #endregion

        #region get solution list event
        [Common.Subscribe]
        public void OnReceiveNCLGetSolutionListEvent(Coolzon.Event.NCL.NCLGetSolutionListEvent @event)
        {
            if (@event.State != Coolzon.Event.NCL.NCLEventState.Sending)
            {
                return;
            }
            ReqGetSolutionListData requestData = new ReqGetSolutionListData();

            Request request = ServiceProxy.RequestUtil.BuildRequest(
                UIContext.Current.ControlDomainId,
                UIContext.Current.UserIdentity,
                REQUEST_SCENARIO.CONNENT,
                REQUEST_COMMAND.CONNECT.GETSOLUTIONLIST,
                REQUEST_MODE.SELF,
                requestData);

            try
            {
                ServiceProxy.ClientProxyManager.Instance.SendRequestSys(request);
                Common.Logger.InfoToTag("RemoteEventProxy", "向服务器发送请求获取方案列表成功");
            }
            catch(Exception ex)
            {
                @event.State = NCLEventState.Failure;
                @event.Error = ex;
                Common.Logger.ErrorToTag("RemoteEventProxy", "向服务器发送请求获取方案列表失败，ex:{0}", ex);
                NCLEventBus.PublishAsync(@event);
            }
        }
        #endregion

        #region login event
        [Common.Subscribe]
        public void OnReceiveNCLLoginEvent(NCLLoginEvent @event)
        {
            if (@event.State != NCLEventState.Sending)
            {
                return;
            }
            ReqLoginData requestData = new ReqLoginData();
            requestData.AppType = @event.AppType;
            requestData.AppVersion = @event.AppVersion;
            requestData.DotNetVersion = @event.DotNetVersion;
            requestData.OSVersion = @event.OSVersion;
            requestData.SolutionSelectionMode = @event.SolutionSelectionMode;
            requestData.StartupPath = @event.StartupPath;
            requestData.UserAccount = @event.UserAccount;
            requestData.UserPassword = @event.UserPassword;
            CPPEI.Coolzon.ServiceProxy.MainServiceRef.Request request = RequestUtil.BuildRequest(
                UIContext.Current.ControlDomainId,
                UIContext.Current.UserIdentity,
                Service.Contract.REQUEST_SCENARIO.CONNENT,
                Service.Contract.REQUEST_COMMAND.CONNECT.LOGIN,
                Service.Contract.REQUEST_MODE.SELF,
                requestData);

            try
            {
                // 初始化所有的客户端代理实例
                if (ServiceProxy.ClientProxyManager.Instance.InitClientProxyList(RemoteEventProxy.Instance))
                {
                    ServiceProxy.ClientProxyManager.Instance.SendRequestSys(request);
                    Common.Logger.InfoToTag("RemoteEventProxy", "向服务器发送登录请求成功");
                }
                else
                {
                    NCLLoginEvent @failureEvent = @event.Clone();
                    @failureEvent.State = NCLEventState.Failure;
                    Common.Logger.ErrorToTag("RemoteEventProxy", "初始化客户端代理实例失败");
                    NCLEventBus.PublishAsync(@failureEvent);
                }
            }
            catch (Exception ex)
            {
                NCLLoginEvent @failureEvent = @event.Clone();
                @failureEvent.State = NCLEventState.Failure;
                Common.Logger.ErrorToTag("RemoteEventProxy", "向服务器发送登录请求失败，ex:{0}", ex);
                NCLEventBus.PublishAsync(@failureEvent);
            }
        }
        #endregion

        #region loading finished event

        [Subscribe]
        public void OnReceiveSolutionLoadingFinishedEvent(UI.Views.SolutionLoadingFinishedEvent @event)
        {
            ReqLoadingFinishedData requestData = new ReqLoadingFinishedData();

            Request request = ServiceProxy.RequestUtil.BuildRequest(
                UIContext.Current.ControlDomainId,
                UIContext.Current.UserIdentity,
                REQUEST_SCENARIO.SOLUTION,
                REQUEST_COMMAND.SOLUTION.LOADINGFINISHED,
                REQUEST_MODE.NORESPONSE,
                requestData);
            ServiceProxy.ClientProxyManager.Instance.SendRequestSys(request);
        }
        #endregion

        #region PartAction Event
        [Common.Subscribe(typeof(EventContext))]
        public void OnPartEvent(EventContext context)
        {
            Coolzon.UI.Data.OpenSceneArgs args = new Coolzon.UI.Data.OpenSceneArgs();
            foreach (string key in context.Arguments.Keys)
            {
                args.ParametersString.Add(key, context.Arguments[key]);
            }

            //// 获取场景定义
            //Metadata.Scene scene = Metadata.SolutionUtil.GetScene(RenderView.Solution, context.TargetSceneName);
            //if (context.ActionType == "REPLACE")
            //{
            //    Common.EventBus.Instance.Publish(new OpenSceneEvent(SwitchMode.Replace, context.TargetFrameName, context.TargetSceneName, args));
            //}
            //else if (context.ActionType == "POP")
            //{
            //    // 弹出视图
            //    Common.EventBus.Instance.Publish(new OpenSceneEvent(SwitchMode.Pop, context.TargetFrameName, context.TargetSceneName, args));
            //}
        }
        #endregion

        #region ScrollToArea Event
        [Subscribe]
        public void OnScrollToArea(ScrollSceneEvent @event)
        {
            //throw new NotImplementedException();
            this.RenderView.ScrollToArea(@event.Scene, @event.Area);
        }

        #endregion

        #region LoopScene Event

        [Subscribe]
        public void OnLoopScene(LoopSceneEvent @event)
        {
            // 在线模式，将事件转交给服务器
            ReqLoopSceneData requestData = new ReqLoopSceneData();
            requestData.Direction = @event.Direction;
            requestData.SceneName = @event.Scene;
            requestData.OffsetDelta = @event.Offset;
            // 获取视图状态
            requestData.ViewStateAge = RenderView.GetViewState().Age;
            requestData.ViewStateToken = RenderView.GetViewStateToken();

            Request request = ServiceProxy.RequestUtil.BuildRequest(
                UIContext.Current.ControlDomainId,
                UIContext.Current.UserIdentity,
                REQUEST_SCENARIO.SCENE,
                REQUEST_COMMAND.SCENE.LOOPSCENE,
                REQUEST_MODE.UNDERCONTROL,
                requestData);
            ServiceProxy.ClientProxyManager.Instance.SendRequestSys(request);
            //Common.Logger.InfoToTag("RemoteEventProxy", string.Format("执行MainService滚动场景:{0},方向:{1},偏移值:{2}！", requestData.SceneName, requestData.Direction, requestData.OffsetDelta));
        }

        [Subscribe]
        public void OnLoopSceneCompleted(LoopSceneCompletedEvent @event)
        {
            RenderView.LoopScene(@event.Direction, @event.Offset);
        }
        #endregion

        #region OpenScene Event

        /// <summary>
        /// 打开场景
        /// </summary>
        /// <param name="@event"></param>
        [Subscribe]
        public void OnReceiveCoreOpenSceneEvent(Coolzon.Event.Core.CoreOpenSceneEvent @event)
        {
            RenderView.OpenScene(SwitchMode.Replace, @event.FrameName, "", @event.SceneName, @event.Args);
        }

        [Subscribe]
        public void OnReceiveNCLOpenSceneEvent(NCLOpenSceneEvent @event)
        {
            if (@event.State != NCLEventState.Sending)
            {
                return;
            }

            if (UIContext.Current.EventProcessMode == Views.EventProcessMode.Online)
            {
                if (RenderView.CurrentScene!= null && string.Equals(RenderView.CurrentScene.Name, @event.SceneName))
                {
                    Common.Logger.WarningToTag("RemoteEventProxy", "接收到NCLOpenSceneEvent场景:{0}，但是当前场景是{1}，不发送",
                        @event.SceneName,
                        RenderView.CurrentScene.Name);
                    return;
                }
                else if (RenderView.CurrentScene != null && string.Equals(_latestOpenScene, @event.SceneName))
                {
                    if (DateTime.Now.Ticks - _latestOpenSceneTicks < TimeSpan.FromSeconds(5).Ticks)
                    {
                        // 5秒内不重复发送
                        Common.Logger.WarningToTag("RemoteEventProxy", "接收到NCLOpenSceneEvent场景:{0}，但是此场景{1}已经发送过打开指令，本次不发送",
                            @event.SceneName,
                            _latestOpenScene);
                        return;
                    }
                }

                // 在线模式，将事件转交给服务器
                ReqOpenSceneData reqOpenSceneData = new ReqOpenSceneData();
                reqOpenSceneData.SwitchMode = @event.SwitchMode.ToString();
                reqOpenSceneData.SceneName = @event.SceneName;
                reqOpenSceneData.ParameterString = Coolzon.UI.Data.OpenSceneArgs.GetParametersString(@event.Args);
                reqOpenSceneData.FrameName = @event.FrameName;

                // 获取视图状态
                reqOpenSceneData.ViewStateAge = RenderView.GetViewState().Age;
                reqOpenSceneData.ViewStateToken = RenderView.GetViewStateToken();

                Request request = ServiceProxy.RequestUtil.BuildRequest(
                    UIContext.Current.ControlDomainId,
                    UIContext.Current.UserIdentity,
                    REQUEST_SCENARIO.SCENE,
                    REQUEST_COMMAND.SCENE.OPENSCENE,
                    REQUEST_MODE.UNDERCONTROL_AND_INDOMAIN,
                    reqOpenSceneData);
                try
                {
                    ServiceProxy.ClientProxyManager.Instance.SendRequest(request);

                    //拦截操作
                    string args = Coolzon.UI.Data.OpenSceneArgs.GetParametersString(@event.Args);
                    string scriptCode = string.Format("window.openScene('{0}','{1}')", @event.SceneName, args);

                    if (@event.SwitchMode.Equals(SwitchMode.Replace))
                    {
                        Common.EventBus.Instance.Publish(new UI.Views.InterceptActionEvent("openScene", scriptCode));
                    }
                    else
                    {
                        Common.EventBus.Instance.Publish(new UI.Views.InterceptActionEvent("popScene", scriptCode));
                    }

                    Common.Logger.InfoToTag("RemoteEventProxy",
                        "执行MainService替换场景:{0},打开模式:{1},用户: {2}执行成功！",
                        @event.SceneName,
                        @event.SwitchMode,
                        UIContext.Current.UserIdentity);

                    _latestOpenSceneTicks = DateTime.Now.Ticks;
                    _latestOpenScene = @event.SceneName;
                }
                catch (Exception ex)
                {
                    @event.State = NCLEventState.Failure;
                    @event.Error = ex;
                    NCLEventBus.PublishAsync(@event);
                }
            }
            else if (!UIContext.Current.IsUnderControl
                || UIContext.Current.EventProcessMode == Views.EventProcessMode.OutOfControl)
            {
                // 不受控制,直接处理
                RenderView.OpenScene(@event.SwitchMode, @event.FrameName, "", @event.SceneName, @event.Args);
                
                @event.State = NCLEventState.Finished;
                NCLEventBus.PublishAsync(@event);
            }
            else if (UIContext.Current.EventProcessMode == Views.EventProcessMode.UnderControl)
            {
                // 受控制,不处理
                return;
            }
        }

        #endregion

        #region CloseScene Event

        [Subscribe]
        public void OnReceiveCoreCloseSceneEvent(Coolzon.Event.Core.CoreCloseSceneEvent @event)
        {
            RenderView.OnBack(@event.SwitchMode,
                @event.FrameName, 
                "SCENE",
                @event.SceneName);
        }

        [Subscribe]
        public void OnReceiveNCLCloseSceneEvent(Coolzon.Event.NCL.NCLCloseSceneEvent @event)
        {
            if (@event.State != NCLEventState.Sending)
            {
                return;
            }

            try
            {
                // 将事件转交给服务器
                ReqCloseSceneData reqCloseSceneData = new ReqCloseSceneData();
                reqCloseSceneData.FrameName = @event.FrameName;
                reqCloseSceneData.SceneName = @event.SceneName;
                reqCloseSceneData.Mode = @event.SwitchMode.ToString();
                // 获取视图状态
                reqCloseSceneData.ViewStateAge = RenderView.GetViewState().Age;
                reqCloseSceneData.ViewStateToken = RenderView.GetViewStateToken();

                Request request = ServiceProxy.RequestUtil.BuildRequest(
                    UIContext.Current.ControlDomainId,
                    UIContext.Current.UserIdentity,
                    REQUEST_SCENARIO.SCENE,
                    REQUEST_COMMAND.SCENE.CLOSESCENE,
                    REQUEST_MODE.UNDERCONTROL,
                    reqCloseSceneData);
                ServiceProxy.ClientProxyManager.Instance.SendRequest(request);
            }
            catch (Exception ex)
            {
                @event.State = NCLEventState.Failure;
                @event.Error = ex;

                Coolzon.Event.NCL.NCLEventBus.PublishAsync(@event);
            }
        }

        #endregion

        #region Mouse Handler

        [Obsolete]
        [SubscribeAttribute(typeof(Event.PartMouseEvent))]
        public void OnReceivePartMouseEvent(Event.PartMouseEvent partMouseEvent)
        {
            try
            {
                ReqMouseEventData reqMouseEventData = new ReqMouseEventData();
                reqMouseEventData.EventSource = partMouseEvent.Source;

                reqMouseEventData.PartName = partMouseEvent.Part;
                reqMouseEventData.PointX = partMouseEvent.X;
                reqMouseEventData.PointY = partMouseEvent.Y;


                Request request = ServiceProxy.RequestUtil.BuildRequest(
                    UIContext.Current.ControlDomainId,
                    UIContext.Current.UserIdentity,
                    REQUEST_SCENARIO.SCENE,
                    REQUEST_COMMAND.SCENE.MOUSEEVENT,
                    REQUEST_MODE.UNDERCONTROL,
                    reqMouseEventData);
                ServiceProxy.ClientProxyManager.Instance.SendRequest(request);
                Common.Logger.InfoToTag("RemoteEventProxy", string.Format("执行MainService鼠标事件:{0},组件名称: {1}  执行成功！", partMouseEvent.Source, partMouseEvent.Part));
            }
            catch (Exception e)
            {
                Common.Logger.InfoToTag("RemoteEventProxy", string.Format("执行MainService鼠标事件:{0},组件名称: {1}  执行失败！", partMouseEvent.Source, partMouseEvent.Part));
            }
        }

        #endregion

        #region Set Property Xml String Handler

        /// <summary>
        /// 收到设置组件属性的变动事件，然后转发到服务器上
        /// </summary>
        /// <param name="event"></param>
        [Subscribe]
        public void OnReceiverSetPropertyXmlStringEvent(Event.SetPropertyXmlStringEvent @event)
        {
            try
            {
                ReqSetPropertyXmlStringData requestData = new ReqSetPropertyXmlStringData();
                requestData.SceneName = @event.SceneName;
                requestData.PartName = @event.PartName;
                requestData.PropertyName = @event.PropertyName;
                requestData.XmlString = @event.XmlString;


                Request request = ServiceProxy.RequestUtil.BuildRequest(
                    UIContext.Current.ControlDomainId,
                    UIContext.Current.UserIdentity,
                    REQUEST_SCENARIO.SCENE,
                    REQUEST_COMMAND.SCENE.SETPROPERTYXMLSTRING,
                    REQUEST_MODE.UNDERCONTROL,
                    requestData);
                ServiceProxy.ClientProxyManager.Instance.SendRequestSys(request);
            }
            catch (Exception ex)
            {
                Common.Logger.InfoToTag("RemoteEventProxy", "执行MainService设置组件属性场景:{0},组件名称: {1} ，属性：{2} 执行失败，ex：{3}！",
                    @event.SceneName,
                    @event.PartName,
                    @event.XmlString,
                    ex);
            }
        }

        #endregion

        #region magnify scene Handler
        [Subscribe]
        public void OnReceiveNCLShowMagnifierEvent(NCLShowMagnifierEvent @event)
        {
            if (@event.State != NCLEventState.Sending)
            {
                return;
            }

            try
            {
                ReqMagnifySceneData requestData = new ReqMagnifySceneData();
                requestData.SceneName = @event.SceneName;
                requestData.DestPointX = @event.DestPointX;
                requestData.DestPointY = @event.DestPointY;
                requestData.DestRadius = @event.DestRadius;
                requestData.IsEnable = @event.IsEnable;
                requestData.Rate = @event.Rate;
                requestData.Duration = @event.Duration;

                Request request = ServiceProxy.RequestUtil.BuildRequest(
                    UIContext.Current.ControlDomainId,
                    UIContext.Current.UserIdentity,
                    REQUEST_SCENARIO.SCENE,
                    REQUEST_COMMAND.SCENE.MAGNIFYSCENE,
                    REQUEST_MODE.UNDERCONTROL,
                    requestData);
                ServiceProxy.ClientProxyManager.Instance.SendRequestSys(request);
            }
            catch (Exception ex)
            {
                Common.Logger.InfoToTag("RemoteEventProxy", "执行MainService放大场景事件出错，ex：{0}！",
                    ex);
                @event.State = NCLEventState.Failure;
                @event.Error = ex;
                NCLEventBus.PublishAsync(@event);
            }
        }

        #endregion

        #region show laser pointer event
        [Subscribe]
        public void OnReceiveNCLShowLaserPointerEvent(NCLShowLaserPointerEvent @event)
        {
            if (@event.State != NCLEventState.Sending)
            {
                return;
            }
            
            try
            {
                ReqShowLaserPointerData requestData = new ReqShowLaserPointerData();
                requestData.SceneName = @event.SceneName;
                requestData.DestPointX = @event.DestPointX;
                requestData.DestPointY = @event.DestPointY;
                requestData.DestRadius = @event.DestRadius;
                requestData.IsShow = @event.IsEnable;
                requestData.Color = @event.Color;
                requestData.Duration = @event.Duration;

                Request request = ServiceProxy.RequestUtil.BuildRequest(
                    UIContext.Current.ControlDomainId,
                    UIContext.Current.UserIdentity,
                    REQUEST_SCENARIO.SCENE,
                    REQUEST_COMMAND.SCENE.SHOWLASERPOINTER,
                    REQUEST_MODE.UNDERCONTROL,
                    requestData);
                ServiceProxy.ClientProxyManager.Instance.SendRequestSys(request);
            }
            catch (Exception ex)
            {
                Common.Logger.InfoToTag("RemoteEventProxy", "执行MainService显示激光笔事件出错，ex：{0}！",
                    ex);
                @event.State = NCLEventState.Failure;
                NCLEventBus.PublishAsync(@event);
            }
        }
        #endregion

        #region scene Mouse Handler

        /// <summary>
        /// 收到场景中的鼠标事件
        /// </summary>
        /// <param name="event"></param>
        [Subscribe]
        public void OnReceiveSceneMouseEvent(Event.SceneMouseEvent @event)
        {
            if (!UIContext.Current.IsConsoleClient())
            {
                return;
            }

            Service.Contract.ReqMouseEventData requestData = new Service.Contract.ReqMouseEventData();
            requestData.SceneName = @event.SceneName;
            requestData.PartName = @event.PartName;
            requestData.EventSource = @event.MouseEventType;
            requestData.PointX = @event.Point.X;
            requestData.PointY = @event.Point.Y;
            ServiceProxy.ClientProxyManager.Instance.SendRequest(
                UIContext.Current.ControlDomainId,
                UIContext.Current.UserIdentity,
                Service.Contract.REQUEST_SCENARIO.SCENE,
                Service.Contract.REQUEST_COMMAND.SCENE.MOUSEEVENT,
                Service.Contract.REQUEST_MODE.UNDERCONTROL,
                requestData);
        }
        #endregion

        #region SwapArea Handler

        [SubscribeAttribute(typeof(Event.SwapAreaEvent))]
        public void OnReceiveSwapAreaEvent(Event.SwapAreaEvent swapAreaEvent)
        {
            try
            {
                ReqSwapAreaData reqSwapAreaData = new ReqSwapAreaData();
                reqSwapAreaData.Scene = swapAreaEvent.Scene;
                reqSwapAreaData.DestArea = swapAreaEvent.DestArea;
                reqSwapAreaData.SourceArea = swapAreaEvent.SourceArea;
                // 获取视图状态
                reqSwapAreaData.ViewStateAge = RenderView.GetViewState().Age;
                reqSwapAreaData.ViewStateToken = RenderView.GetViewStateToken();

                Request request = ServiceProxy.RequestUtil.BuildRequest(
                    UIContext.Current.ControlDomainId,
                    UIContext.Current.UserIdentity,
                    REQUEST_SCENARIO.SCENE,
                    REQUEST_COMMAND.SCENE.SWAPAREA,
                    REQUEST_MODE.UNDERCONTROL,
                    reqSwapAreaData);
                ServiceProxy.ClientProxyManager.Instance.SendRequest(request);
                Common.Logger.InfoToTag("RemoteEventProxy", string.Format("执行MainService场景区域互换事件:{0},源区域名称: {1},目标区域名称:{2}  执行成功！", "SwapAreaEvent", swapAreaEvent.SourceArea,swapAreaEvent.DestArea));
            }
            catch (Exception e)
            {
                Common.Logger.InfoToTag("RemoteEventProxy", string.Format("执行MainService场景区域互换事件:{0},源区域名称: {1},目标区域名称:{2}  执行失败！", "SwapAreaEvent", swapAreaEvent.SourceArea, swapAreaEvent.DestArea));
            }
        }

        #endregion

        #region TabChange Handler

        [SubscribeAttribute(typeof(Event.TabChangeEvent))]
        public void OnReceiveTabChangeEvent(Event.TabChangeEvent tabChangeEvent)
        {
            if (!UIContext.Current.IsConsoleClient())
            {
                return;
            }

            try
            {
                ReqTabChangeData reqTabChangeData = new ReqTabChangeData();
                reqTabChangeData.Scene = tabChangeEvent.Scene;
                reqTabChangeData.NewTabIndex = tabChangeEvent.NewTabIndex;
                reqTabChangeData.OldTabIndex = tabChangeEvent.OldTabIndex;
                reqTabChangeData.TabContainer = tabChangeEvent.TabContainer;

                // 获取视图状态
                reqTabChangeData.ViewStateAge = RenderView.GetViewState().Age;
                reqTabChangeData.ViewStateToken = RenderView.GetViewStateToken();

                Request request = ServiceProxy.RequestUtil.BuildRequest(
                    UIContext.Current.ControlDomainId,
                    UIContext.Current.UserIdentity,
                    REQUEST_SCENARIO.TABCONTAINER,
                    REQUEST_COMMAND.TABCONTAINER.CHANGE,
                    REQUEST_MODE.UNDERCONTROL,
                    reqTabChangeData);

                ServiceProxy.ClientProxyManager.Instance.SendRequest(request);

                Common.Logger.InfoToTag("RemoteEventProxy", string.Format("执行MainService选项卡切换事件:{0},原选项卡序号: {1},新选项卡序号:{2},场景:{3},选项卡容器:{4}  执行成功！", "TabChangeEvent", tabChangeEvent.OldTabIndex, tabChangeEvent.NewTabIndex, tabChangeEvent.Scene, tabChangeEvent.TabContainer));
            }
            catch (Exception e)
            {
                Common.Logger.InfoToTag("RemoteEventProxy", string.Format("执行MainService选项卡切换事件:{0},原选项卡序号: {1},新选项卡序号:{2},场景:{3},选项卡容器:{4}  执行失败！", "TabChangeEvent", tabChangeEvent.OldTabIndex, tabChangeEvent.NewTabIndex, tabChangeEvent.Scene, tabChangeEvent.TabContainer));
            }
        }

        #endregion

        #region change control state event

        /// <summary>
        /// 接收到修改控制状态的事件，向服务器转发
        /// </summary>
        /// <param name="event"></param>
        [Subscribe]
        public void OnReceiveNCLChangeControlStateEvent(Coolzon.Event.NCL.NCLChangeControlStateEvent @event)
        {
            if (@event.State != Coolzon.Event.NCL.NCLEventState.Sending)
            {
                return;
            }
            try
            {
                ReqChangeControlStateEventData requestData = new ReqChangeControlStateEventData(
                    @event.ControlState,
                    UIContext.Current.UserIdentity,
                    UIContext.Current.Solution.Name,
                    UIContext.Current.ControlDomainId);

                Request request = ServiceProxy.RequestUtil.BuildRequest(
                    UIContext.Current.ControlDomainId,
                    UIContext.Current.UserIdentity,
                    REQUEST_SCENARIO.SETTING,
                    REQUEST_COMMAND.SETTING.CHANGECONTROLSTATE,
                    REQUEST_MODE.SELF,
                    requestData);

                ServiceProxy.ClientProxyManager.Instance.SendRequestSys(request);
                Common.Logger.InfoToTag("RemoteEventProxy", string.Format("向服务器发送控制状态修改事件，controlState:{0}", requestData.ControlState));
            }
            catch (Exception ex)
            {
                @event.State = NCLEventState.Failure;
                @event.Error = ex;
                Coolzon.Event.NCL.NCLEventBus.PublishAsync(@event);
                Common.Logger.ErrorToTag("RemoteEventProxy", string.Format("向服务器发送控制状态修改事件失败，ex：{0}", ex));
            }
        }

        #endregion

        #region reset scene

        /// <summary>
        /// 接收到来自ui的场景重置事件，发送网络数据到服务器
        /// </summary>
        /// <param name="event"></param>
        [Subscribe]
        public void OnReceiveBeginResetSceneEvent(UI.Views.Events.BeginResetSceneEvent @event)
        {
            Service.Contract.ReqResetSceneData responseData = new ReqResetSceneData();
            responseData.SceneName = @event.SceneName;

            ServiceProxy.ClientProxyManager.Instance.SendRequest(UIContext.Current.ControlDomainId,
                UIContext.Current.UserIdentity,
                Service.Contract.REQUEST_SCENARIO.SETTING,
                Service.Contract.REQUEST_COMMAND.SETTING.RESETSCENE,
                Service.Contract.REQUEST_MODE.UNDERCONTROL,
                responseData);
        }

        #endregion

        #region reset solution
        
        /// <summary>
        /// 接收到来自ui的方案重置事件，发送网络数据到服务器
        /// </summary>
        /// <param name="event"></param>
        [Subscribe]
        public void OnReceiveBeginResetSolutionEvent(UI.Views.Events.BeginResetSolutionEvent @event)
        {
            Service.Contract.ReqResetSolutionData responseData = new ReqResetSolutionData();
            responseData.SolutionName = @event.SolutionName;

            ServiceProxy.ClientProxyManager.Instance.SendRequestSys(UIContext.Current.ControlDomainId,
                UIContext.Current.UserIdentity,
                Service.Contract.REQUEST_SCENARIO.SETTING,
                Service.Contract.REQUEST_COMMAND.SETTING.RESETSOLUTION,
                Service.Contract.REQUEST_MODE.UNDERCONTROL_AND_INDOMAIN,
                responseData);
        }

        #endregion

        #region execute js event

        [Subscribe]
        public void OnReceiveExecuteJsEvent(Event.ExecuteJSEvent @event)
        {
            RenderView.ExecuteJs(@event.ScriptCode);
        }

        #endregion

        #region switch solution event

        /// <summary>
        /// 接收到请求切换方案的事件
        /// </summary>
        /// <param name="event"></param>
        [Subscribe]
        public void OnReceiveNCLSwitchSolutionEvent(CPPEI.Coolzon.Event.NCL.NCLSwitchSolutionEvent @event)
        {
            if (@event.State != NCLEventState.Sending)
            {
                return;
            }
            ReqSwitchSolutionData requestData = new ReqSwitchSolutionData();
            requestData.SolutionName = @event.SolutionName;

            Request request = ServiceProxy.RequestUtil.BuildRequest(
                UIContext.Current.ControlDomainId,
                UIContext.Current.UserIdentity,
                REQUEST_SCENARIO.SOLUTION,
                REQUEST_COMMAND.SOLUTION.SWITCH,
                REQUEST_MODE.UNDERCONTROL,
                requestData);
            ServiceProxy.ClientProxyManager.Instance.SendRequestSys(request);
        }

        #endregion

        #region sync view state 
        [Subscribe]
        public void OnReceiverSyncViewStateEventEvent(SyncViewStateEvent @event)
        {
            ReqSyncViewStateData requestData = new ReqSyncViewStateData();
            requestData.IsImperative = @event.IsImperative;

            Request request = ServiceProxy.RequestUtil.BuildRequest(
                UIContext.Current.ControlDomainId,
                UIContext.Current.UserIdentity,
                REQUEST_SCENARIO.CONNENT,
                REQUEST_COMMAND.CONNECT.SYNCVIEWSTATE,
                REQUEST_MODE.SELF,
                requestData);
            ServiceProxy.ClientProxyManager.Instance.SendRequestSys(request);
        }
        #endregion

        #region get domain instance mode
        public void OnReceiveGetDomainInstanceModeEvent(NCLGetDomainInstanceModeEvent @event)
        {
            if (@event.State == NCLEventState.Sending)
            {
                ReqGetDomainInstanceModeData requestData = new ReqGetDomainInstanceModeData();
                Request request = ServiceProxy.RequestUtil.BuildRequest(
                    UIContext.Current.ControlDomainId,
                    UIContext.Current.UserIdentity,
                    REQUEST_SCENARIO.CONNENT,
                    REQUEST_COMMAND.CONNECT.GETDOMAININSTANCEMODE,
                    REQUEST_MODE.SELF,
                    requestData);
                ServiceProxy.ClientProxyManager.Instance.SendRequestSys(request);
            }
        }
        #endregion

        #region core event

        #region part event

        /// <summary>
        /// 收到组件交互事件
        /// </summary>
        /// <param name="event"></param>
        [Subscribe]
        public void OnReceiveCorePartEvent(Coolzon.Event.Core.CorePartEvent @event)
        {
            ReqPartEventData requestData = new ReqPartEventData();
            requestData.PartName = @event.PartName;
            requestData.ClientID = @event.ClientID;
            requestData.EventName = @event.EventName;
            requestData.EventData = @event.Data;

            Request request = ServiceProxy.RequestUtil.BuildRequest(
                UIContext.Current.ControlDomainId,
                UIContext.Current.UserIdentity,
                REQUEST_SCENARIO.SCENE,
                REQUEST_COMMAND.SCENE.PARTEVENT,
                REQUEST_MODE.UNDERCONTROL_AND_INDOMAIN,
                requestData);
            try
            {
                ServiceProxy.ClientProxyManager.Instance.SendRequestSys(request);
            }
            catch (Exception ex)
            {
                Common.Logger.ErrorToTag("RemoteEventProxy", "发送组件:{0}交互事件失败,ex:{1}", @event.PartName, ex);
            }
        }

        #endregion

        #endregion

        #region ShowQueryPanel event

        [Subscribe]
        public void OnReceiveCoreShowQueryPanelEvent(CPPEI.Coolzon.Event.Core.CoreShowQueryPanelEvent @event)
        {
            // 控件组件
            QueryView queryView = new QueryView(((Metadata.NodeBase)@event.PartMetadata).Parameters);
            queryView.Tag = @event.PartInstance;
            queryView.Close += queryView_Close;
            UIContext.Current.RootViewContainer.PopView((@event.PartInstance as ScenePart).Caption, queryView);
        }

        void queryView_Close(View view, bool isCancel)
        {
            QueryView queryView = view as QueryView;
            UI.Part partInstance = view.Tag as UI.Part;

            List<Metadata.Parameter> returnParameters = queryView.Results;
            if (returnParameters == null)
            {
                return;
            }

            if (partInstance is Part)
            {
                // 控件组件
                for (int index = 0; index < queryView.Results.Count; index++)
                {
                    partInstance.Parameters.Set(queryView.Results[index]);
                }
            }
        }

        #endregion

        #region script net event
        [Subscribe]
        public void OnReceiveNCLSendScriptNetEventEvent(CPPEI.Coolzon.Event.NCL.NCLSendScriptNetEventEvent @event)
        {
            if (@event.State != NCLEventState.Sending)
            {
                return;
            }
            ReqScriptNetEventData requestData = new ReqScriptNetEventData();
            requestData.Scene = @event.Scene;
            requestData.EventName = @event.EventName;
            requestData.DataString = @event.DataString;

            Request request = ServiceProxy.RequestUtil.BuildRequest(
                UIContext.Current.ControlDomainId,
                UIContext.Current.UserIdentity,
                REQUEST_SCENARIO.SCENE,
                REQUEST_COMMAND.SCENE.SCRIPTNETEVENT,
                REQUEST_MODE.UNDERCONTROL_AND_INDOMAIN,
                requestData);
            ServiceProxy.ClientProxyManager.Instance.SendRequest(request);
        }
        #endregion

        #region update client status

        /// <summary>
        /// 接收到网络事件，要求更新终端的状态
        /// </summary>
        /// <param name="event"></param>
        [Subscribe]
        public void OnReceiveNCLUpdateClientStatusEvent(NCLUpdateClientStatusEvent @event)
        {
            Service.Contract.ReqUpdateClientStatusData responseData = new ReqUpdateClientStatusData();
            responseData.Status = @event.Status;

            ServiceProxy.ClientProxyManager.Instance.SendRequestSys(UIContext.Current.ControlDomainId,
                UIContext.Current.UserIdentity,
                Service.Contract.REQUEST_SCENARIO.CONNENT,
                Service.Contract.REQUEST_COMMAND.CONNECT.UPDATECLIENTSTATUS,
                Service.Contract.REQUEST_MODE.NORESPONSE,
                responseData);
        }
        #endregion

        #region check client status
        [Subscribe]
        public void OnReceiveNCLBeginCheckClientStatusEvent(NCLBeginCheckClientStatusEvent @event)
        {
            Service.Contract.ReqCheckClientStatusData responseData = new ReqCheckClientStatusData();
            responseData.Status = @event.Status;

            ServiceProxy.ClientProxyManager.Instance.SendRequestSys(UIContext.Current.ControlDomainId,
                UIContext.Current.UserIdentity,
                Service.Contract.REQUEST_SCENARIO.CONNENT,
                Service.Contract.REQUEST_COMMAND.CONNECT.CHECKCLIENTSTATUS,
                Service.Contract.REQUEST_MODE.SELF,
                responseData);
        }
        #endregion


        #region GetViewState
        [Subscribe]
        public void OnReceiveNCLBeginGetViewStateEvent(NCLBeginGetViewState @event)
        {
            Service.Contract.ReqGetViewStateData responseData = new ReqGetViewStateData(@event.SolutionName, @event.MainServerIp, @event.MainServerPort);

            ServiceProxy.ClientProxyManager.Instance.SendRequestSys(UIContext.Current.ControlDomainId,
                UIContext.Current.UserIdentity,
                Service.Contract.REQUEST_SCENARIO.CONNENT,
                Service.Contract.REQUEST_COMMAND.CONNECT.GETVIEWSTATE,
                Service.Contract.REQUEST_MODE.SELF,
                responseData);
        }
        #endregion
    }
}
